import { defineStore } from "pinia";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useModalStore } from "@/store/modal.js";

const modal = useModalStore();

export const useUserStore = defineStore(
  "user",
  () => {
    // 当前登录用户名称
    const currentUser = ref("");
    // 是否登录
    const isLogin = ref(false);
    // 注册的用户信息
    const users = ref({
      account: "",
      password: "",
    });

    // 登录
    const login = (account, password) => {
      const foundUser =
        users.value.account === account && users.value.password === password;
      if (foundUser) {
        ElMessage({
          message: "登录成功!",
          type: "success",
        });
        isLogin.value = true;
        currentUser.value = foundUser.account;
        modal.switchLoginVisible();
      } else {
        ElMessage({
          message: "账号或者密码错误!",
          type: "warning",
        });
      }
    };

    // 退出登录
    const logout = () => {
      isLogin.value = false;
      currentUser.value = "";
    };

    // 注册更新用户信息
    const register = (account, password) => {
      users.value = { account, password };
      isLogin.value = true;
    };
    return { currentUser, isLogin, users, login, register, logout };
  },
  {
    persist: {
      enabled: true, //Store中数据持久化生效
    },
  }
);
